package com.adee.juc;

import com.adee.util.Utils;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁使用
 */
public class Test008_ReentrantReadWriteLock {
    public static void main(String[] args) {
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock rLock = rwLock.readLock();
        ReentrantReadWriteLock.WriteLock wLock = rwLock.writeLock();
        int[] arr = new int[3];
        Runnable reader = ()->{
            for (;;) {
                rLock.lock();
                try {
                    Utils.sleepMills(300);
                    Utils.print(arr);
                }finally {
                    rLock.unlock();
                }
            }
        };
        Runnable writer = ()->{
            for (;;) {
                Utils.sleep(3);
                wLock.lock();
                try {
                    Utils.sleep(3);
                    for (int i = 0; i < arr.length; i++) {
                        arr[i] += 1;
                    }
                }finally {
                    wLock.unlock();
                }
            }
        };
        new Thread(reader).start();
        new Thread(writer).start();
    }
}
